<template>
	<div class="all">
		<el-form class="form" label-width="70" :model="form" :rules="rules" ref="ruleFormRef">
			<el-form-item label="用户名" class="form_item" prop="account">
				<el-input v-model="form.account"></el-input>
			</el-form-item>

			<el-form-item label="密码" class="form_item" prop="password">
				<el-input :type="flagType" v-model="form.password">
					<template #suffix>
						<el-icon size="20" @click="changePwdHide">
							<View v-if="!pwIsHide" />
							<Hide v-if="pwIsHide" />
						</el-icon>
					</template>
				</el-input>
			</el-form-item>

			<el-form-item label="" class="form_item">
				<el-button type="primary" class="button" @click="doLogin">提交</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="ts" name="loginIndex">
import { onMounted, ref, reactive, computed } from 'vue';
import { NextLoading } from '/@/utils/loading';
import type { FormInstance, FormRules } from 'element-plus';
import { login } from '/@/api/api';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { Session } from '/@/utils/storage';

interface RuleForm {
	account: string;
	password: string;
}

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules<RuleForm>>({
	account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
	password: [
		{
			required: true,
			message: '请输入密码',
			trigger: 'blur',
		},
	],
});

const form = reactive({});
const pwIsHide = ref(true);
const flagType = ref('password');
const route = useRoute();
const router = useRouter();

function changePwdHide() {
	pwIsHide.value = !pwIsHide.value;
	flagType.value = !pwIsHide.value ? 'text' : 'password'; //text为显示密码；password为隐藏密码
}

async function doLogin() {
	let { code, result } = await login({
		...form,
	});
	if (code == 200) {
		Session.set('token', result.token);
		const isNoPower = await initFrontEndControlRoutes();
		signInSuccess(isNoPower);
	}
}

const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中

		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/userlist');
		}
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style scoped lang="scss">
.all {
	display: flex;
	display: flex;
	text-align: center;
	justify-content: center;
	align-items: center;
}

.form {
	display: flex;
	flex-direction: column;
}

.form_item {
	width: 400px;
}

.button {
	background-color: #1677ff;
	width: 80px;
	height: 30px;
	box-shadow: 0 0 5px #ccc;
}
</style>
